﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using RooHui.Infrastructure.Configuration;
using RooHui.Infrastructure.Entities.EFContext;
using System.Data.SqlClient;
using RooHui.Tool;

namespace RooHui.Application.CommonWebLogic
{
    [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class)]
    public class OperationTraceAttribute : FilterAttribute, IActionFilter
    {
        public void OnActionExecuted(ActionExecutedContext filterContext)
        {
        }

        public void OnActionExecuting(ActionExecutingContext filterContext)
        {
            string url = filterContext.HttpContext.Request.UrlReferrer.ToString();
            if (OperationTraceSettings.Dict.ContainsKey(url))
            {
                var item = OperationTraceSettings.Dict[url];
                if (item.Log && (item.Method.ToUpper() == "ALL" ||
                    item.Method.ToUpper() == filterContext.RequestContext.HttpContext.Request.HttpMethod.ToUpper()))
                {
                    string sqlString = "insert into P_MenberLog values(@userName,@OperateType,@OperateIP,@OperateContent,getdate())";
                    try
                    {
                        Context.AsyncExcuteNonQuery(sqlString, null,
                            new SqlParameter("@userName", System.Data.SqlDbType.VarChar) { Value = filterContext.HttpContext.User.Identity.Name },
                            new SqlParameter("@OperateType", System.Data.SqlDbType.Int) { Value = item.OperateType },
                            new SqlParameter("@OperateIP", System.Data.SqlDbType.VarChar) { Value = filterContext.HttpContext.Request.ServerVariables["REMOTE_ADDR"].ToString() },
                            new SqlParameter("@OperateContent", System.Data.SqlDbType.VarChar)
                            {
                                Value = string.Format(item.Format.Templete,
                                    item.Format.paramList.Select(p =>
                                    filterContext.HttpContext.Request.QueryString[p]).ToArray())
                            });
                    }
                    catch (Exception e)
                    {
                        LogHelper.Write(CommonLogger.Application, LogLevel.Error, e);
                    }
                }
            }
        }
    }
}
